<?php
class Application_Model_PacientesMapper
{
	protected $_dbTable;

	/**
	 * Method setDbTable
	 */
	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	/**
	 * Method getDbTable
	 */
	public function getDbTable()
	{
		if (is_null($this->_dbTable)) {
			$this->setDbTable('Application_Model_DbTable_Pacientes');
		}
		return $this->_dbTable;
	}

	/**
	 * Method fetchAll
	 *
	 * @return array
	 */
	public function fetchAll()
	{
		$rowset = $this->getDbTable()->fetchAll();
		return $this->_processRowset($rowset);
	}

	/**
	 * Method search
	 *
	 * @param string $string
	 * @return array
	 */
	public function search($string)
	{
		$table = $this->getDbTable();
		$rowset = $table->fetchAll(
			$table->select()
			->where('`nombre` LIKE ?', '%' . utf8_decode($string) . '%')
			->orWhere('`apellidos` LIKE ?', '%' . utf8_decode($string) . '%')
			->limit(50)
		);
		return $this->_processRowset($rowset);
	}

	/**
	 * Method _processRowset
	 *
	 * @param Zend_Db_Table_Rowset $rowset
	 * @return array
	 */
	private function _processRowset($rowset)
	{
		$entries = array();
		foreach ($rowset as $row) {
			$entry = new Application_Model_Pacientes();
			$entry->setId($row->id)
				  ->setDni($row->dni)
				  ->setNombre(utf8_encode($row->nombre))
				  ->setApellidos(utf8_encode($row->apellidos))
				  ->setNacimiento($row->nacimiento);
			$entries[] = $entry;
		}
		return $entries;
	}

}
